package com.tnl.web.config.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.biz.hunter.dao.CompanyDAO;
import com.biz.hunter.dao.DomainDAO;
import com.biz.hunter.dao.EmployerDAO;
import com.biz.hunter.dao.TempCompanyDAO;
import com.biz.hunter.db.entity.Company;
import com.biz.hunter.db.entity.Domain;
import com.biz.hunter.db.entity.Employer;
import com.biz.hunter.db.entity.HunterCompany;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.CompanyDto;
import com.tnl.web.dto.JqGridPage;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.util.qualifiers.AuditIt;

@Controller
public class CompanyController {
	private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);
	
	@Autowired
	private CompanyDAO companyDAO;

	@Autowired
	private TempCompanyDAO tempCompanyDAO;

	@Autowired
	private EmployerDAO employerDAO;
	
	@Autowired
	private DomainDAO domainDAO;
	
	@Autowired
	private Authentication authentication;
	
	//公司管理
	@AuditIt(module = "Company", action = "company_view", description = "Show the company index page")
	@RequestMapping(value = "admin/company/manage.page", method = RequestMethod.GET)
	public String companyManagement(HttpServletRequest request, Model model) {
		
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {

			logger.info("empty user id ,session is not initiallized.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}
		
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/company/companylist";

	}

	// 显示编辑表单页面
	@AuditIt(module = "Company", action = "editCompany", description = "Show company edit page")
	@RequestMapping(value = "admin/company/form.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, Model model) {

		String companyid = request.getParameter("companyid");
		Company cp = null;
		if (StringUtils.hasText(companyid)) {
			cp = companyDAO.getById(Integer.parseInt(companyid));
			model.addAttribute("company", cp);
		} else {
			return "admin/errorpage";
		}
		
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/company/companyeditform";
	}

	// 显示公司详细信息页面
	@RequestMapping(value = "admin/company/detail.page", method = RequestMethod.GET)
	public String companyDetail(HttpServletRequest request, Model model) {

		String companyid = request.getParameter("companyid");
		
		Company cp = null;
		if (StringUtils.hasText(companyid)) {
			cp = companyDAO.getById(Integer.parseInt(companyid));
			model.addAttribute("company", cp);
		} else {
			return "admin/errorpage";
		}
		
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/company/companydetail";
	}

	// 搜索数据
	@RequestMapping(value = "admin/company/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Company> searchCompany(jqGridRequestObject request, String sname, String sphone, Integer sstatus) {
		
		jqGridResponseObject<Company> msg = new jqGridResponseObject<Company>();
		
		long page = request.getPage();
		long pagesize = request.getRows();
		
		long totalrows = request.getTotalrows();
		long totalpages = 0;
		
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = companyDAO.getCountOfAll(sname, sphone,sstatus);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
		
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;
		
		List<Company> list = companyDAO.getAllWithLimit(sname, sphone,sstatus, start, pagesize);
		
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
		
		return msg;
	}
	
	// 删除数据
	@AuditIt(module = "Company", action = "deleteCompany", description = "Delete company action")
	@RequestMapping(value = "admin/company/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteCompany(HttpServletRequest request, Integer companyid) {
			
		ErrorMsg msg = new ErrorMsg();
			
		if (companyid == null) {
			logger.debug("companyid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}

		int result = companyDAO.delete(String.valueOf(companyid));
		if (result == 1) {
			msg.setErrorcode("0");
			msg.setMsg("删除成功");
			return msg;
		}

		msg.setErrorcode("50001");
		msg.setMsg("删除失败");
		return msg;
	}

	// 更新数据
	@AuditIt(module = "Company", action = "editCompany", description = "update company action")
	@RequestMapping(value = "admin/company/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateCompany(HttpServletRequest request,  Company company) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if(company == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司信息");
			return msg;
		}
		if(company.getId() <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司信息");
			return msg;
		}
		
		Company cp = companyDAO.getById(company.getId());
		if(cp == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该公司");
			return msg;
		}
		
		cp.setName(company.getName());
		cp.setAddress(company.getAddress());
		cp.setApproved(1);
		cp.setContact(company.getContact());
		cp.setLicenseCode(company.getLicenseCode());
		cp.setOrgnizationCode(company.getOrgnizationCode());
		cp.setDomain(company.getDomain());

		int result = companyDAO.update(cp);
		if (result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新数据失败");
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("数据更新成功");
		return msg;
	}
	
	
	@RequestMapping(value = "admin/company/toView.page", method = RequestMethod.GET)
	public Company getCompanyDetail(
			@RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
		Company company = tempCompanyDAO.getById(id);
		return company;
	}	

	@RequestMapping(value = "admin/company/getAllCompany.do", method = RequestMethod.GET)
	@ResponseBody
	public JqGridPage getAllCompany(JqGridPage page) {
		List<Company> list = tempCompanyDAO.getALL();
		Page<Company> companies = new PageImpl<Company>(list,
				page.toPageable(), list.size());
		page = JqGridPage.valueOf(companies);
		return page;
	}
	
	/*
	@RequestMapping(value = "admin/company/manage.page", method = RequestMethod.GET)
	public String getCompanies(ModelMap model) {
		List<Company> list = tempCompanyDAO.getALL();
		model.addAttribute("tempCompanies", list);
		return "admin/company/list";
	}
	*/
	
	
	@ResponseBody
	@RequestMapping(value = "admin/company/getDomainCompanies", method = RequestMethod.GET)
	public List<Company> getDomainCompanies(
			@RequestParam(value = "domainId", required = true, defaultValue = "0") Integer domainId) {
		List<Company> list = companyDAO.getDomainCompanies(domainId);
		return list;
	}

	@RequestMapping(value = "admin/company/create.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg createCompany(@RequestBody Company company) {
		logger.info("Start create Company.");
		ErrorMsg msg = new ErrorMsg();
		Date now = new Date();
		company.setCreateDate(now.getTime());
		int result = tempCompanyDAO.save(company);
		if (result == -1) {
			logger.error("create company failed" + company);
			return null;
		}

		company.setId(result);
		return msg;
	}

	@RequestMapping(value = "admin/company/deactiveCompany.do", method = RequestMethod.DELETE)
	public @ResponseBody ErrorMsg deactiveCompany(@PathVariable("id") int Id) {
		logger.info("Start delete Company.");
		ErrorMsg msg = new ErrorMsg();
		Company company = tempCompanyDAO.getById(Id);
		company.setApproved(-1);
		tempCompanyDAO.update(company);
		return msg;
	}
	
	/*
	@RequestMapping(value = "admin/company/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateCompany(@RequestBody Company company) {
		logger.info("Start UPDATE Company.");
		ErrorMsg msg = new ErrorMsg();
		Company current = tempCompanyDAO.getById(company.getId());
		convertCompany(company, current);
		tempCompanyDAO.update(current);
		return msg;
	}
	*/
	
	private void convertCompany(Company srcCompany, Company destCompany) {
		destCompany.setContact(srcCompany.getContact());
		destCompany.setEmail(destCompany.getEmail());
		// ... TODO：

	}

	// 认证一个公司，就是把temp公司转为公司的过程。
	@RequestMapping(value = "admin/company/authorize.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> authorizeCompany(
			HttpServletRequest request, int hunterId, int tempId, int companyId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Employer employer = employerDAO.getById(hunterId);
		if (employer == null) {
			map.put("errorcode", "500");
			map.put("msg", "can not find the hunter with the provided id ="
					+ hunterId);
			return map;
		}
//		if (employer.getCompanyId() != 0) {
//			map.put("errorcode", "500");
//			return map;
//		}
		if (!StringUtils.hasText(employer.getCompanyName())) {
			map.put("errorcode", "500");
			return map;
		}

		Company tempCompany = tempCompanyDAO.getById(tempId);
		if (employer.getCompanyId() != 0) {
			map.put("errorcode", "500");
			return map;
		}

		Company company = companyDAO.getById(companyId);
		if (company == null) {
			int id = companyDAO.save(tempCompany);
			if (id != -1) {
				tempCompanyDAO.deleteById(tempId);
			}
			employer.setCompanyName(null);
			employer.setCompanyId(id);
			employerDAO.update(employer);
			map.put("errorcode", "200");
			map.put("msg", "success");
			return map;
		} else {

			employer.setCompanyName(null);
			employer.setCompanyId(companyId);
			employerDAO.update(employer);
			map.put("errorcode", "200");
			map.put("msg", "success");
			return map;
		}
	}

	// 将一个终端用户输入的公司，转为 一个认证公司
	@RequestMapping(value = "admin/company/mergeCompany.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> mergeCompany(
			HttpServletRequest request, int hunterId, int tempId, int companyId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorcode", "200");
		map.put("msg", "success");
		return map;
	}
	
	@AuditIt(module = "Company", action = "createCompany", description = "create company action")
	@RequestMapping(value = "wechat/company/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> persistentCompany(
			HttpServletRequest request, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("openId");

		int hrId = dto.getHrid();
		if (hrId == 0) {
			logger.error("the input hr id is 0");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hrId");
			return returnMap;
		}
		Employer employer = employerDAO.getById(hrId);
		if (employer == null) {
			logger.error("can not get the employer by the provided id" + hrId);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hr id = "
					+ hrId);
			return returnMap;
		}

		int companyId = persistentCompany(dto);
		if (companyId == -1) {
			logger.error("failed to persistent Company");
			returnMap.put("errorcode", "50105");
			returnMap.put(
					"msg",
					" failed to persistent the  company ("
							+ dto.getCompanyname() + ")  Id ="
							+ dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}
		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}
	
	private int persistentCompany(CompanyDto dto) {
		int companyId = dto.getCompanyid();

		Company comp = tempCompanyDAO.getById(companyId);
		if (comp != null) {// update
			// 认证通过，不再update
			if (comp.getApproved() == 1) {
				return companyId;
			}
			comp.setName(dto.getCompanyname());
			comp.setContact(dto.getCompanycontact());
			comp.setAddress(dto.getCompanyaddress());
			// comp.setEmail(dto.);
			comp.setPhone(dto.getCompanyphone());
			comp.setLicenseCode(dto.getBizcode());
			comp.setOrgnizationCode(dto.getOrgcode());
			comp.setCreateId(dto.getHrid());
			int result = tempCompanyDAO.update(comp);
			if (result == -1) {
				logger.error("failed to update hunter comapny" + companyId);
				return -1;
			}
			return companyId;
		}
		int hrId = dto.getHrid();
		comp = tempCompanyDAO.getByEmployerId(hrId);
		if (comp != null) {
			logger.error("ther user has already created one company.");
			return -1;
		}
		// create new company
		comp = new Company();
		comp.setName(dto.getCompanyname());
		comp.setContact(dto.getCompanycontact());
		comp.setAddress(dto.getCompanyaddress());
		// comp.setEmail(dto.);
		comp.setPhone(dto.getCompanyphone());
		comp.setLicenseCode(dto.getBizcode());
		comp.setOrgnizationCode(dto.getOrgcode());
		comp.setApproved(0);
		Date now = new Date();
		comp.setCreateDate(now.getTime());
		comp.setCreateId(dto.getHrid());
		int result = tempCompanyDAO.save(comp);
		if (result == -1) {
			logger.error("failed to update hunter comapny" + comp.getName());
			return -1;
		}
		// companyId = comp.getId();

		return result;
	}
}